local hats = { }

local function CreateHat( pl, model )
	SafeRemoveEntity( pl.Hat )

	local hat

	hat = ClientsideModel( model, RENDERGROUP_OPAQUE )
	hat:SetNoDraw( true )

	pl.Hat = hat
	hat.Owner = pl
	table.insert( hats, hat )
end

local function CleanHats( )
	local k, v

	for k, v in pairs( hats ) do
		if not IsValid( v ) then
			hats[ k ] = nil
		elseif not IsValid( v.Owner ) then
			SafeRemoveEntity( v )
			hats[ k ] = nil
		end
	end
end

local function DrawHats( )
	local k, v, pos, ang

	CleanHats( )

	for k, v in ipairs( player.GetAll( ) ) do
		if not v:Alive( ) and IsValid( v.Hat ) then
			SafeRemoveEntity( v.Hat )
			v = v:GetRagdollEntity( )
		else
			CreateHat( v, "models/vikinghelmet/vikinghelmet.mdl" )
		end

		pos, ang = v:GetBonePosition( ply:LookupBone("ValveBiped.Bip01_Head1") )

		v.Hat:SetPos( pos * .01)
		v.Hat:SetAngles( ang )
		v.Hat:DrawModel( )
	end
end

hook.Add( "PostDrawOpaqueRenderables", "Draw Hats.PostDrawOpaqueRenderables", DrawHats )